package com.aihongbo.service.t1

import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.aihongbo.service.t1.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val TAG = MainActivity::class.java.simpleName
    private lateinit var binding: ActivityMainBinding
    private var logService: LogService? = null
    private var logService1: LogService1? = null

    private var conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?, service: IBinder?
        ) {
            Log.d(TAG, "服务启动")
            logService = (service as LogService.LogBinder).getService()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "服务停止")
        }
    }

    private var conn1: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            name: ComponentName?, service: IBinder?
        ) {
            logService1 = (service as LogService1.LogBinder).service
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //启动服务
//        startService(Intent(this, LogService::class.java))

        //绑定服务
        bindService(Intent(this, LogService::class.java), conn, BIND_AUTO_CREATE)
//        bindService(Intent(this, LogService1::class.java), conn1, BIND_AUTO_CREATE)

        //开始执行
        binding.button.setOnClickListener {
            logService1?.start()
            logService?.start()
        }

        //结束执行
        binding.button2.setOnClickListener {
            logService1?.stop()
            logService?.stop()
        }
    }
}